package cifg;

import com.iid.flappybird.R;


import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

import cifgb.CSSDBEAN;
import cifgu.SKINADATPEW;
import cifgu.SKINADATPEV;

public class GAMEVIEW extends SurfaceView implements Callback, Runnable {

    private SurfaceHolder sfh;
    private Paint paint;

    private Thread th;
    private boolean flag;

    private Canvas canvas;
    private static int screenW, screenH;

    private static final int GAME_MENU = 0;
    private static final int GAMEING = 1;
    private static final int GAME_OVER = -1;

    private static int gameState = GAME_MENU;

    private int[] floor = new int[2];
    private int floor_width = 15;

    private int speed = 3;

    private int[] level = new int[2];
    private int level_value = 0;

    private int[] bird = new int[2];
    private int bird_width = 10;
    private int bird_v = 0;
    private int bird_a = 2;
    private int bird_vUp = -16;


    private ArrayList<int[]> walls = new ArrayList<int[]>();
    private ArrayList<int[]> remove_walls = new ArrayList<int[]>();
    private int wall_w = 50;
    private int wall_h = 100;

    private int wall_step = 30;
    private int start_wall_step = 30;

    private int[] pointColorArr;

    private boolean firstClickScreen = true;

    private GAMEACT gameBirdActivity;

    private MessageListener messageListener;

    private Drawable skinDrawable;

    private boolean drawOk = false;

    public GAMEACT getGameBirdActivity() {
        return gameBirdActivity;
    }

    public void setGameBirdActivity(GAMEACT gameBirdActivity) {
        this.gameBirdActivity = gameBirdActivity;
    }

    public MessageListener getMessageListener() {
        return messageListener;
    }

    public void setMessageListener(MessageListener messageListener) {
        this.messageListener = messageListener;
    }

    public interface MessageListener {
        void scoreChange(int score);

        void gameOver(int score);

        void gameStart();
    }

    public GAMEVIEW(Context context) {
        super(context);
        init();
    }

    private void init() {
        pointColorArr = new int[5];
        pointColorArr[0] = R.color.black;
        pointColorArr[1] = R.color.title_backBlue;
        pointColorArr[2] = R.color.ruleritemline;
        pointColorArr[3] = R.color.col_FF3B;
        pointColorArr[4] = R.color.col_1677f;
        sfh = this.getHolder();
        sfh.addCallback(this);
        paint = new Paint();
        paint.setColor(getContext().getColor(pointColorArr[generate(0, 4)]));
        paint.setAntiAlias(true);
        paint.setTextSize(50);
        paint.setStrokeWidth(10);
        paint.setStyle(Style.STROKE); //空心

        int skinId = SKINADATPEV.getInt(getContext(), SKINADATPEW.Skin_Id, 1);
        if (skinId == 1) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_cattle);
        } else if (skinId == 2) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_hema);
        } else if (skinId == 3) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_monkey);
        } else if (skinId == 4) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_pony);
        } else if (skinId == 5) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_rat);
        } else if (skinId == 6) {
            skinDrawable = getContext().getDrawable(R.drawable.skin_tiger);
        }
        setFocusable(true);
        setFocusableInTouchMode(true);

        this.setKeepScreenOn(true);
    }


    public static int generate(int min, int max) {
        Random random = new Random();
        return random.nextInt((max - min) + 1) + min;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawOk = true;

        screenW = this.getWidth();
        screenH = this.getHeight();

        //System.out.println("=======screenW="+screenW+"=======screenH="+screenH);

        initGame();

        flag = true;

        th = new Thread(this);
        th.start();
    }

    private void initGame() {

        if (gameState == GAME_MENU) {

            floor[0] = 0;
            floor[1] = screenH - screenH / 5;//  最底部墙的位置

            level[0] = screenW / 2;
            level[1] = screenH / 5; // 当前得分

            level_value = 0;

            bird[0] = screenW / 3;
            bird[1] = screenH / 2; // 小球起点位置

            walls.clear();

            //dp to px
            floor_width = dp2px(15);

            speed = dp2px(3);

            bird_width = dp2px(10);
            bird_a = dp2px(2);
            bird_vUp = -dp2px(10);

            wall_w = dp2px(70);
            wall_h = dp2px(170);
            start_wall_step = dp2px(30);

            wall_step = wall_w * 3;
        }
    }

    private int dp2px(float dp) {
        int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
        return px;
    }

    public void myDraw() {
        if (drawOk) {
            try {
                canvas = sfh.lockCanvas();
                if (canvas != null) {
                    //clear
                    canvas.drawColor(Color.WHITE);
                    //background
//                int floor_start = floor[0];
//                while (floor_start < screenW) {
//                    canvas.drawLine(floor_start, floor[1], floor_start + floor_width, floor[1], paint);
//                    floor_start += floor_width * 2;
//                }

                    canvas.drawLine(0, floor[1], screenW, floor[1], paint);

                    //wall
                    for (int i = 0; i < walls.size(); i++) {
                        int[] wall = walls.get(i);

                        float[] pts = {
                                wall[0], 0, wall[0], wall[1],
                                wall[0], wall[1] + wall_h, wall[0], floor[1],
                                wall[0] + wall_w, 0, wall[0] + wall_w, wall[1],
                                wall[0] + wall_w, wall[1] + wall_h, wall[0] + wall_w, floor[1],
                                wall[0], wall[1], wall[0] + wall_w, wall[1],
                                wall[0], wall[1] + wall_h, wall[0] + wall_w, wall[1] + wall_h
                                //,wall[0],floor[1], wall[0]+wall_w, floor[1]
                        };
                        canvas.drawLines(pts, paint);

                        //canvas.drawRect(wall[0], 0, wall[0]+wall_w, wall[1], paint);
                        //canvas.drawRect(wall[0], wall[1]+wall_h, wall[0]+wall_w, floor[1], paint);
                    }

                    //bird
//                canvas.drawCircle(bird[0], bird[1], bird_width, paint);
                    skinDrawable.setBounds(bird[0], bird[1], bird[0] + (bird_width * 2), bird[1] + (bird_width * 2));
                    skinDrawable.draw(canvas);

                    messageListener.scoreChange(level_value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (canvas != null && sfh != null) {
                    sfh.unlockCanvasAndPost(canvas);
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            switch (gameState) {
                case GAME_MENU:
                    gameState = GAMEING;
                    if (messageListener != null) {
                        messageListener.gameStart();
                    }
//					bird_v = bird_vUp;
//					break;
                case GAMEING:
                    bird_v = bird_vUp;
                    break;
                case GAME_OVER:
                    //bird down
                    if (bird[1] >= floor[1] - bird_width) {
                        gameState = GAME_MENU;
                        initGame();
                    }
                    break;
            }
        }
        return true;
    }

    private int move_step = 0;

    private void logic() {

        switch (gameState) {
            case GAME_MENU:

                break;
            case GAMEING:

                //bird
                bird_v += bird_a;
                bird[1] += bird_v;
                if (bird[1] > floor[1] - bird_width) {
                    bird[1] = floor[1] - bird_width;
                    gameState = GAME_OVER;
                }
                //top
//				if(bird[1]<=bird_width){
//					bird[1]=bird_width;
//				}

                //floor
                if (floor[0] < -floor_width) {
                    floor[0] += floor_width * 2;
                }
                floor[0] -= speed;

                //wall
                remove_walls.clear();
                for (int i = 0; i < walls.size(); i++) {
                    int[] wall = walls.get(i);
                    wall[0] -= speed;
                    if (wall[0] < -wall_w) {
                        remove_walls.add(wall);
                    } else if (wall[0] - bird_width <= bird[0] && wall[0] + wall_w + bird_width >= bird[0]
                            && (bird[1] <= wall[1] + bird_width || bird[1] >= wall[1] + wall_h - bird_width)) {
                        gameState = GAME_OVER;
                    }

                    int pass = wall[0] + wall_w + bird_width - bird[0];
                    if (pass < 0 && -pass <= speed) {
                        level_value++;
                    }
                }
                //out of screen
                if (remove_walls.size() > 0) {
                    walls.removeAll(remove_walls);
                }

                //new wall
                move_step += speed;
                if (move_step > start_wall_step) {
                    start_wall_step = wall_step;
                    int[] wall = new int[]{screenW, (int) (Math.random() * (floor[1] - 2 * wall_h) + 0.5 * wall_h)};
                    walls.add(wall);
                    move_step = 0;
                }

                if (level_value % 2 == 0) {
                    wall_step = wall_w * generate(2, 3);
                }
                break;
            case GAME_OVER:
                //bird
                if (bird[1] < floor[1] - bird_width) {
                    bird_v += bird_a;
                    bird[1] += bird_v;
                    if (bird[1] >= floor[1] - bird_width) {
                        bird[1] = floor[1] - bird_width;
                    }
                } else {
                    messageListener.gameOver(level_value);
                    gameState = GAME_MENU;
                    initGame();
                }
                break;

        }
    }

    @Override
    public void run() {
        while (flag) {
            long start = System.currentTimeMillis();
            myDraw();
            logic();
            long end = System.currentTimeMillis();
            try {
                if (end - start < 50) {
                    Thread.sleep(50 - (end - start));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        drawOk = false;
        flag = false;
    }

    public void Destroy() {
        gameState = GAME_MENU;
        sfh = null;
        initGame();
    }
}
